/*
 * HandlerEngine.java
 *
 * Created on August 22, 2007, 11:25 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.infoset.xml.util;

import org.infoset.xml.Item;
import org.infoset.xml.ItemDestination;
import org.infoset.xml.XMLException;

/**
 *
 * @author alex
 */
public class HandlerEngine implements ItemDestination
{
   
   public interface Handler extends ItemDestination {
      void init(HandlerEngine engine);
      int getStartLevel();
      Handler pop();
   }
   
   int level;
   Handler current;
   /** Creates a new instance of HandlerEngine */
   public HandlerEngine()
   {
      this(null);
   }
   public HandlerEngine(Handler current)
   {
      this.level = 0;
      this.current = current;
      if (current!=null) {
         current.init(this);
      }
   }
   
   public int getLevel() {
      return level;
   }
   
   public Handler getCurrentHandler() {
      return current;
   }
   
   public void push(Handler handler)
      throws XMLException
   {
      push(handler,null);
   }
   public void push(Handler handler,Item item)
      throws XMLException
   {
      handler.init(this);
      current = handler;
      if (item!=null) {
         current.send(item);
      }
   }
   
   public void send(Item item)
      throws XMLException
   {
      switch (item.getType()) {
         case ElementItem:
            level++;
            break;
      }
      current.send(item);
      switch (item.getType()) {
         case ElementEndItem:
            level--;
            if (level<current.getStartLevel()) {
               current = current.pop();
            }
      }
   }
}
